//
//  ViewController.swift
//  lesson7闭包的参数和返回值
//
//  Created by 张建 on 2018/3/16.
//  Copyright © 2018年 micheal. All rights reserved.
//

import UIKit
let kScreenWidth = UIScreen.main.bounds.size.width
let kScreenHeight = UIScreen.main.bounds.size.height


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let customView = createView(itemNumber: 15) { (index) -> UIView in

            let btnWidth = 60
            let btn = UIButton()
            btn.addTarget(self, action: #selector(clickBtn(sender:)), for: .touchUpInside)
            btn.tag = index
            btn.frame = CGRect(x: index*btnWidth ,y:20 ,width:btnWidth ,height:40)
            btn.backgroundColor = UIColor.orange
            btn.setTitle("按钮\(index)", for: .normal)
            btn.setTitleColor(UIColor.black, for: .normal)
            return btn
        }
        
//        let customView = createView(itemNumber: 8) { (index) -> UIView in
//
//            let btnWidth = 60
//            let label = UILabel(frame: CGRect(x: index*btnWidth, y: 20, width: btnWidth, height: 40))
//            label.text = "按钮\(index)"
//            label.backgroundColor = UIColor.red
//            return label
//        }
        view.addSubview(customView)
        
    }
    
    func createView(itemNumber: Int,buildItemBlock: (_ index: Int) -> UIView) -> UIView {
        
        //创建一个scrollView
        let scrView = UIScrollView(frame: CGRect(x: 0, y: 100, width:kScreenWidth ,height:80))
        scrView.backgroundColor = UIColor.green
        //创建按钮
       
        for index in 0...itemNumber {
            
            let btn = buildItemBlock(index)
            scrView.contentSize = CGSize(width: (index+1)*Int(btn.frame.size.width),height:80)
            scrView.addSubview(btn)
        }
        return scrView
    }
    
    @objc func clickBtn(sender: UIButton) {
        
        let btn = sender
        print("点击了按钮\(btn.tag)")
    }
}

